using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NiSis.Data.SqlClient;
using NiSis.Data;
using NiSis.Entities;

namespace NiSis.UserControls
{
    /// <summary>
    /// Visualizza l'elenco dei pools da attivare per una data. La data e selezionabile tramite
    /// il controllo mese anno picker interno.
    /// </summary>
    public partial class PoolsToActivate : System.Web.UI.UserControl
    {
        private string mMeseFornitura;
        protected VPool CurrentPool
        {
            set
            {
                HdCurrentPool.Value = String.Format("{0}|{1}|{2}|{3}",
                    value.CdPool, value.CdShipperDefault, value.CdMeseInizioFornitura, value.IdStato);
            }
            get
            {
                VPool newPool = new VPool();
                string[] mt = HdCurrentPool.Value.Split('|');
                if (mt.Length < 3)
                    return new VPool();

                newPool.CdPool = mt[0];
                newPool.CdShipperDefault = mt[1];
                newPool.CdMeseInizioFornitura = mt[2];
                newPool.IdStato = (mt[3] == string.Empty ? 0 : int.Parse(mt[3]));
                return newPool;
            }
        }

        private VList<VPool> mLPools;

        public VList<VPool> LPools
        {
            get
            {
                if (mLPools == null && HdCurrentPool.Value != string.Empty)
                    mLPools = DataRepository.VPoolProvider.Get(
                        string.Format("cd_pool='{0}' and cd_mese_inizio_fornitura='{1}'",
                        CurrentPool.CdPool, CurrentPool.CdMeseInizioFornitura), string.Empty);
                return mLPools;
            }
            set { mLPools = value; }
        }

        public string MeseFornitura
        {
            get { return MeseAnnoPicker1.DateValue; }
            set { mMeseFornitura = value; }
        }

        public bool AutoPostBack
        {
            get { return LstPools.AutoPostBack; ; }
            set { LstPools.AutoPostBack = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            mMeseFornitura = MeseAnnoPicker1.DateValue;
            setUsrNotInPoolHeaderVisible(mMeseFornitura != string.Empty);
            if (!Page.IsPostBack)
                setUsrNotInPoolHeaderVisible(false);

        }

        void Page_PreRender(Object o, EventArgs e)
        {
            if (this.Visible)
                SetColors(); //questa proprieta non tiene dopo le posback, deve essere ricalcolata ogni volta     
        }



        public void setUsrNotInPoolHeaderVisible(bool val)
        {
            PnlLinks.Visible = val;

            //btexpand.Visible = val;
            //btCollapse.Visible = val;
            if (!val)
                lblTitle.Text = string.Empty;
            else
                lblTitle.Text = "Seleziona un pool";
        }
        #region 'SelectedPoolChanged' event definition code
        /// <summary>
        ///     EventArgs derived type which holds the custom event fields
        /// </summary>
        [Serializable]
        public class SelectedPoolChangedEventArgs : System.EventArgs
        {
            /// <summary>
            ///     Use this constructor to initialize the event arguments
            ///     object with the custom event fields
            /// </summary>
            public SelectedPoolChangedEventArgs(string cdMeseAnno, string newCdPool, SshStatoRelazioniList stato)
            {
                _cdMeseAnno = cdMeseAnno;
                _newCdPool = newCdPool;
                _stato = stato;
            }

            private string _cdMeseAnno;

            public string CdMeseAnno
            {
                get { return _cdMeseAnno; }
                set { _cdMeseAnno = value; }
            }

            private string _newCdPool;

            public string NewCdPool
            {
                get { return _newCdPool; }
                set { _newCdPool = value; }
            }

            private SshStatoRelazioniList _stato;

            public SshStatoRelazioniList Stato
            {
                get { return _stato; }
                set { _stato = value; }
            }


        }

        /// <summary>
        ///     This represents the delegate method prototype that
        ///     event receivers must implement
        /// </summary>
        public delegate void SelectedPoolChangedEventHandler(object sender, SelectedPoolChangedEventArgs e);

        /// <summary>
        ///     TODO: Describe the purpose of SelectedPoolChanged here
        /// </summary>
        public event SelectedPoolChangedEventHandler SelectedPoolChanged;

        /// <summary>
        ///     This is the method that is responsible for notifying
        ///     receivers that the event occurred
        /// </summary>
        protected virtual void OnSelectedPoolChanged(SelectedPoolChangedEventArgs e)
        {
            if (SelectedPoolChanged != null)
            {
                SelectedPoolChanged(this, e);
            }
        }


        #endregion //('SelectedPoolChanged' event definition code)
        private VList<VTradersPrec> mCurrentPools;

        public VList<VTradersPrec> CurrentPools
        {
            get { return mCurrentPools; }
            set { mCurrentPools = value; }
        }
        public void Refresh()
        {
            int sIndex = LstPools.SelectedIndex;
            VList<VPool> Pools = DataRepository.VPoolProvider.Get(String.Format("Cd_Mese_Inizio_Fornitura='{0}' and Cd_Pool is not null", mMeseFornitura), "Cd_Pool");
            Pools = CustomUtil.SelectDistinctFromVList<VPool>(Pools, new Enum[] { VPoolColumn.CdPool });
            LstPools.DataSource = Pools;
            LstPools.Visible = (Pools.Count > 0);
            if (Pools.Count > 0)
                CurrentPool = Pools[0];
            LstPools.DataBind();
            LPools = Pools;
            lblTitle.Visible = Pools.Count > 0;
            ChkConsolidati.Visible = Pools.Count > 0;

            SetColors();
            CheckListState();
            cmdUtNoPool.OnClientClick = string.Format("javascript:window.open('UtenzeNoPool.aspx?CdMese={0}','utenze','location=0,status=1,scrollbars=1'); return false;", mMeseFornitura);
            cmdUtPNotDefined.OnClientClick = string.Format("javascript:window.open('UtenzeNoPoolDefined.aspx?CdMese={0}','utenze','location=0,status=1,scrollbars=1'); return false;", mMeseFornitura);
            if (sIndex >= 0 && sIndex < LstPools.Items.Count)
                LstPools.SelectedIndex = sIndex;

        }
        public void Hide()
        {
            LstPools.Visible = false;
            PnlLinks.Visible = false;
            ChkConsolidati.Visible = false;
            lblTitle.Visible = false;
        }

        public VTradersPrec GetCurrentPool()
        {
            //    //ritorna null per non andare avanti
            //    if (CurrentPool.IdStato == 2 || CurrentPool.IdStato == 3)
            //        return null;

            VPool cPool = (VPool)CurrentPool.Clone();
            cPool.CdPool = LstPools.SelectedValue;
            CurrentPool = cPool;
            return MappingUtil.MapPoolToVtradersPrec(cPool);
        }
        protected void grdUsrNoPools_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
                e.Row.Cells[3].Text = CustomUtil.DataInverter(e.Row.Cells[3].Text);
        }


        protected void MeseAnnoPicker1_MonthSelected(object sender, MeseAnnoPicker.MonthSelectedEventArgs e)
        {
            mMeseFornitura = e.CdMeseAnno;
            Refresh();

        }




        protected void LstPools_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SelectedPoolChangedEventArgs ev = new SelectedPoolChangedEventArgs(MeseAnnoPicker1.DateValue, LstPools.SelectedValue, GetStateFromColors(LstPools.SelectedItem));
                SelectedPoolChanged(this, ev);
            }
            catch (Exception)
            {
            }

        }
        private SshStatoRelazioniList GetLiState(ListItem li)
        {
            VPool pool = LPools.Find("CdPool", li.Value);
            if (pool == null)
                return SshStatoRelazioniList.NonIpotizzato;

            return (SshStatoRelazioniList)pool.IdStato;
        }

        public void SetColors()
        {
            foreach (ListItem li in LstPools.Items)
            {
                //SshStatoRelazioniList st=DataRepositoryUtils.PoolState(li.Value,MeseFornitura);
                SshStatoRelazioniList st = GetLiState(li);
                switch (st)
                {
                    case SshStatoRelazioniList.Confermato:
                        //li.Attributes.CssStyle.Add("COLOR", "#FF0000");
                        li.Attributes.CssStyle.Add("COLOR", System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Green));

                        break;
                    case SshStatoRelazioniList.Consolidato:
                        li.Attributes.CssStyle.Add("COLOR", System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Blue));

                        break;
                    case SshStatoRelazioniList.Ipotizzato:
                        li.Attributes.CssStyle.Add("COLOR", System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Orange));

                        break;
                    case SshStatoRelazioniList.NonIpotizzato:
                        //li.Attributes.CssStyle.Add("COLOR", System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Green));

                        break;
                    case SshStatoRelazioniList.Rifiutato:
                        li.Attributes.CssStyle.Add("COLOR", System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Red));

                        break;
                    default:
                        break;
                }
            }
        }

        protected SshStatoRelazioniList GetStateFromColors(ListItem li)
        {
            string color = li.Attributes.CssStyle.Value;
            switch (color)
            {
                case "COLOR:Green;":
                    return SshStatoRelazioniList.Confermato;
                case "COLOR:Blue;":
                    return SshStatoRelazioniList.Consolidato;
                case "COLOR:Orange;":
                    return SshStatoRelazioniList.Ipotizzato;
                case "COLOR:Red;":
                    return SshStatoRelazioniList.Rifiutato;
                default:
                    return SshStatoRelazioniList.NonIpotizzato;
            }
        }

        public bool CanGoNext()
        {
            SetColors();

            if (LstPools.SelectedItem == null)
                return false;

            if (LstPools.SelectedItem.Attributes.CssStyle.Value == null) //nero
                return true;

            if (LstPools.SelectedItem.Attributes.CssStyle.Value == "COLOR:Red;")
                return true;

            if (LstPools.SelectedItem.Attributes.CssStyle.Value == "COLOR:Orange;")
                return true;

            Refresh();
            return false;
        }
        private void CheckListState()
        {
            List<ListItem> dlt = new List<ListItem>();
            if (ChkConsolidati.Checked)
            {
                foreach (ListItem li in LstPools.Items)
                    if (li.Attributes.CssStyle.Value == "COLOR:Green;" || li.Attributes.CssStyle.Value == "COLOR:Blue;")
                        dlt.Add(li);
                foreach (ListItem li in dlt)
                    LstPools.Items.Remove(li);
            }
            //else
            //    Refresh();
        }
        protected void ChkConsolidati_CheckedChanged(object sender, EventArgs e)
        {
            Refresh();
        }
        protected void LstPools_DataBound(object sender, DataListItemEventArgs e)
        {
            VPool pool = (VPool)e.Item.DataItem;
            e.Item.Attributes.Add("stato", pool.IdStato.ToString());
        }

        protected void cmdUtPNotDefined_Click(object sender, ImageClickEventArgs e)
        {
            cmdUtPNotDefined.OnClientClick = string.Format("javascript:window.open('UtenzeNoPool.aspx?CdMese={0}','utenze','location=0,status=1,scrollbars=1');", mMeseFornitura);
        }

    }
}